package com.analyse.stock.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.analyse.stock.constant.ApiConstant;
import com.analyse.stock.constant.StockConstant;
import com.analyse.stock.enums.IndexCategoryEnum;
import com.analyse.stock.mapper.IndexInfoMapper;
import com.analyse.stock.model.BoardCategoryModel;
import com.analyse.stock.model.CountryInfoModel;
import com.analyse.stock.model.IndexInfoModel;
import com.analyse.stock.service.ICountryInfo;
import com.analyse.stock.service.IIndexInfo;
import com.analyse.stock.utils.HttpUtil;
import com.analyse.stock.utils.StockStringUtil;
import com.analyse.stock.vo.FundFlowDataVO;
import com.analyse.stock.vo.TickerVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Slf4j
@Service
public class IndexInfoService extends ServiceImpl<IndexInfoMapper, IndexInfoModel> implements IIndexInfo {

    @Autowired
    private ICountryInfo countryInfo;

    @Override
    public Integer pullIndexList(String countryCodes) {
        List<CountryInfoModel> countryList = countryInfo.getCountryByCodes(countryCodes);
        if(CollUtil.isEmpty(countryList)){
            return 0;
        }
        List<IndexInfoModel> existList = super.list();
        Set<String> exists = existList.stream().map(IndexInfoModel::getCountryCode).collect(Collectors.toSet());
        AtomicInteger num = new AtomicInteger(0);
        for(CountryInfoModel model : countryList){
            if(exists.contains(model.getCountryCode())){
                continue;
            }
            String url = StrUtil.format(ApiConstant.INDEX_LIST_URL,model.getCountryCode());
            String result = HttpUtil.sendGet(url,"*/*", StockConstant.UTF8,6000L);
            if(StringUtils.isBlank(result)){
                continue;
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            if(jsonObject.getInteger("code") != 200 || Objects.isNull(jsonObject.getJSONArray("data"))){
                continue;
            }
            List<TickerVO> list = JSONObject.parseArray(jsonObject.getString("data"), TickerVO.class);
            List<IndexInfoModel> list2 = list.stream().map(IndexInfoModel::transIndexInfoModel).collect(Collectors.toList());
            log.info("### 国家：{} ,共返回：{} 条 ###",model.getCountryCode(),list2.size());
            super.saveBatch(list2);
            num.getAndAdd(list2.size());
        }
        return num.get();
    }

    @Override
    public Integer pullIndexListByEasyMoney(String countryCode) {
        List<CountryInfoModel> countryList = countryInfo.getCountryByCodes(countryCode);
        if(CollUtil.isEmpty(countryList)){
            return 0;
        }
        CountryInfoModel countryModel = countryList.get(0);
        AtomicInteger num = new AtomicInteger(0);
        for(IndexCategoryEnum categoryEnum : IndexCategoryEnum.values()){
            long time = System.currentTimeMillis()*1001;
            String url = StrUtil.format(ApiConstant.EASYMONEY_INDEX_LIST_URL,categoryEnum.getCode(),time);
            String result = HttpUtil.sendGet(url,"*/*", StockConstant.UTF8,6000L);
            if(StringUtils.isBlank(result)){
                continue;
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            if(jsonObject.getInteger("rc") != 0 || Objects.isNull(jsonObject.get("data"))){
                continue;
            }
            FundFlowDataVO dataVO = StockStringUtil.getObject(jsonObject.getString("data"), FundFlowDataVO.class);
            if(Objects.isNull(dataVO) || dataVO.getTotal()<1){
                continue;
            }
            log.info("## 板块:{}, 开始解析 系列指数数据-----",categoryEnum.getDesc());
            List<IndexInfoModel> list2 = dataVO.getDiff().stream()
                    .map(e->IndexInfoModel.transIndexInfoModel(e,categoryEnum,countryModel.getCountryCode())).collect(Collectors.toList());
            log.info("### 国家：{} ,共返回：{} 条 ###",categoryEnum.getDesc(),list2.size());
            super.saveBatch(list2);
            num.getAndAdd(list2.size());
        }
        return num.get();
    }

    @Override
    public List<IndexInfoModel> getIndexList(String indexCodes) {
        if(StringUtils.isBlank(indexCodes)){
            return super.list();
        }
        LambdaQueryWrapper<IndexInfoModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(IndexInfoModel::getIndexCode, Arrays.asList(indexCodes.split(StrUtil.COMMA)));
        return super.list(wrapper);
    }

    /**
     * http://www.360doc.com/content/23/1225/18/27524644_1108767415.shtml
     * 通过指数判断大盘情绪
     * 1、涨跌家数指标
     * 2、炸板率折线图
     * 3、连板分布图
     * 4、昨日涨停指数，昨日连板指数
     * 5、大盘主力净流入资金
     * 6、成交量涨跌幅，相比昨日，放量滞涨，量价齐升
     */
}
